<?php
class Application_Model_Users extends Zend_Db_Table{
	protected $_name = 'users';
	protected $_primary = 'id';

	public function getAllUsers( $_returnType = null ){
		try{
			$sql = $this->select()->setIntegrityCheck(false)
						->from($this->_name, array('id', 'email', 'username'));

			if ( $_returnType == 'query' ){
				return $sql;
			}

			$result = $this->getAdapter()->fetchAll($sql);
			if( $result )
				return $result;
			else
				return array();
		}
		catch(Zend_Exception $e){
			return array();
		}
	}

	public function getUserByEmail( $_email ){
		try{
			$sql = $this->select()->setIntegrityCheck(false)
						->from($this->_name)
						->where('email = ?', $_email)
						->limit(1);
			$result = $this->fetchRow($sql);

			if( $result )
				return $result->toArray();
			else
				return false;
		}
		catch(Zend_Exception $e){
			return false;
		}
	}

	public function updateUser( $_user ){
		if ( isset( $_user['id'] ) ){
			$where = $this->getAdapter()->quoteInto('id = ?', $_user['id']);
			return $this->update($_user, $where);
		}
	}

	public function getUserByField( $_field_name, $_field_value ){
		try{
			$sql = $this->select()->setIntegrityCheck(false)
						->from($this->_name)
						->joinLeft('acl_role', 'users.acl_role_id = acl_role.id', array('role_name' => 'name'))
						->where($_field_name . ' = ?', $_field_value)
						->limit(1);
			$result = $this->fetchRow($sql);

			if( $result )
				return $result->toArray();
			else
				return false;
		}
		catch(Zend_Exception $e){
			return false;
		}
	}

	public function generateSalt($salt_length = 3) {
		$salt = '';
		for ($i = 0; $i < $salt_length; $i++) {
			$salt .= chr(rand(32, 126));
		}

		return $salt;
	}

	public function saveUser( $data ){
		try {
			if (isset($data['id']) && $data['id'] > 0) {
				if($res = $this->find((int)$data['id'])) {
					$row = $res->current();
					unset($data['id']);
					$row->setFromArray($data);
					$row->save();
					return $row->id;
				}
				else {
					return false;
				}
			}
			else {
				$this->insert($data);
				$lastId = $this->getAdapter()->lastInsertId();
				return $lastId;
			}
		}
		catch(Zend_Exception $e) {
			return false;
		}
	}

}